package com.d3.pomodoro.fragment

import android.os.Bundle
import android.view.*
import androidx.recyclerview.widget.RecyclerView
import com.d3.pomodoro.R
import com.d3.pomodoro.adapter.HomeCateAdapter
import com.d3.pomodoro.component.BottomView
import com.d3.pomodoro.utils.SoftKeyBoardController
import com.orhanobut.logger.Logger
import com.yanzhenjie.recyclerview.touch.OnItemMoveListener
import kotlinx.android.synthetic.main.fragment_main.*
import androidx.recyclerview.widget.LinearLayoutManager
import com.baozi.treerecyclerview.adpater.TreeRecyclerAdapter
import com.baozi.treerecyclerview.adpater.TreeRecyclerType
import com.baozi.treerecyclerview.factory.ItemHelperFactory
import com.d3.pomodoro.component.SpacesItemDecoration
import com.d3.pomodoro.utils.AppUtils
import java.util.*
import com.baozi.treerecyclerview.item.TreeItemGroup
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.d3.pomodoro.component.TomatoClockView
import com.d3.pomodoro.model.*
import com.yanzhenjie.recyclerview.SwipeMenuItem
import kotlin.collections.ArrayList


class MainFragment : BaseFragment() {

    companion object {
        const val MAX_CATE_INPUT_LENGTH = 40
    }

    var homeCateAdapter: HomeCateAdapter? = null
    var cateList: MutableList<Cate> = mutableListOf()

    var treeRecycleAdapter: TreeRecyclerAdapter? = null
    var taskGroupList = ArrayList<ViewModel.TaskGroupItem>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
    }

    override fun initThemeViews() {
        themeController?.mainColorViewList?.add(bottomView)
    }

    override fun getFragmentLayoutId(): Int {
        return R.layout.fragment_main
    }

    override fun onVisibleToUserChanged(isVisibleToUser: Boolean, invokeInResumeOrPause: Boolean) {
        super.onVisibleToUserChanged(isVisibleToUser, invokeInResumeOrPause)
        if (isVisibleToUser) {
            changeStatusBarColor(R.color.d3_light_back_ground)
        }
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when (v?.id) {
            R.id.imageBarCalendar -> {

            }
            R.id.measureDrawerLayout -> showOrDismissDrawer(false)
            else -> {

            }
        }
    }

    override fun initViews() {
        super.initViews()
//        app:navigationIcon="?attr/homeAsUpIndicator"

        showOrDismissDrawer(true)
        measureDrawerLayout.setOnClickListener(this)
        imageBarCalendar.setOnClickListener(this)

        softKeyBoardChangeListener?.setKeyBoardChangeListener(object :
            SoftKeyBoardController.OnSoftKeyBoardChangeListener {
            override fun keyBoardShow(height: Int) {
                bottomView.changeModel(BottomView.ShowModel.EDIT_MODEL)
            }

            override fun keyBoardHide(height: Int) {
                bottomView.changeModel(BottomView.ShowModel.NORMAL_MODEL)
            }
        })

        toolBar?.setOnMenuItemClickListener { menu ->
            when (menu.itemId) {
                R.id.action_about -> {
                    Logger.e("onOptionsItemSelected $menu")

                    true
                }
                else -> false
            }
        }

        tomatoClockView?.apply {
            setTomatoClockViewListener(object : TomatoClockView.TomatoClockViewListener {
                override fun action(action: String) {
                    when (action) {
                        TomatoClockView.ACTION_ZOOM_IN -> {
                            changeStatusBarColor(R.color.d3_light_back_ground)
                        }
                        TomatoClockView.ACTION_ZOOM_OUT -> {
                            changeStatusBarColor(R.color.d3_gray)

                        }
                        TomatoClockView.ACTION_CLICK_MENU -> {

                        }
                        TomatoClockView.ACTION_CLICK_STOP -> {
                            tomatoClockView?.stopTomatoClock()

                        }
                        TomatoClockView.ACTION_START_CLOCK -> {
                            changeStatusBarColor(R.color.d3_gray)

                        }
                        TomatoClockView.ACTION_TIMER_FINISH -> {

                        }
                    }
                }

            })


        }
        cateRecycleView.apply {
            isLongPressDragEnabled = true// 开启长按拖拽
            isItemViewSwipeEnabled = false// 开启滑动删除。
            val layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
            setLayoutManager(layoutManager)
            addItemDecoration(SpacesItemDecoration(AppUtils.dip2px(context, 8f)))

            setOnItemClickListener { view, adapterPosition ->
                showOrDismissDrawer(false)
            }

            setOnItemMoveListener(object : OnItemMoveListener {
                override fun onItemDismiss(srcHolder: RecyclerView.ViewHolder?) {

                    // 从数据源移除该Item对应的数据，并刷新Adapter。
                    if (srcHolder != null) {
                        val position = srcHolder.adapterPosition
                        cateList.removeAt(position)
                        homeCateAdapter?.notifyItemRemoved(position)
                    }

                }

                override fun onItemMove(
                    srcHolder: RecyclerView.ViewHolder?,
                    targetHolder: RecyclerView.ViewHolder?
                ): Boolean {
                    if (srcHolder != null && targetHolder != null) {
                        val fromPosition = srcHolder.adapterPosition
                        val toPosition = targetHolder.adapterPosition
                        Collections.swap(cateList, fromPosition, toPosition)
                        homeCateAdapter?.notifyItemMoved(fromPosition, toPosition)

                        // 返回true，表示数据交换成功，ItemView可以交换位置。
                        return true
                    }
                    return false
                }
            })// 监听拖拽和侧滑删除，更新UI和数据。

            homeCateAdapter = HomeCateAdapter(cateList)
            homeCateAdapter?.setCateClickListener(object : HomeCateAdapter.CateClickListener {
                override fun onClick(holder: BaseViewHolder, item: Cate) {
                    Logger.e("setOnItemClickListener is " + item.title)
                    if (item.isCreateItem) {
                        Logger.e("cate CreateItem")
                    } else {
                        refreshToolBarTitle(item.title)
                    }


                }

            })
            adapter = homeCateAdapter
        }

        baseRecycleView?.apply {
            val layoutManager = LinearLayoutManager(activity)
            setLayoutManager(layoutManager)

            setSwipeMenuCreator { leftMenu, rightMenu, position ->

                val width = AppUtils.dip2px(context, 50f)
                val height = AppUtils.dip2px(context, 50f)
                val layoutId = treeRecycleAdapter?.getLayoutId(position)
                if (layoutId == R.layout.item_task || layoutId == R.layout.item_sub_task) {
                    val finishItem = SwipeMenuItem(context)
                    val addSubItem = SwipeMenuItem(context)
                    val removeItem = SwipeMenuItem(context)
                    val startItem = SwipeMenuItem(context)
                    removeItem.apply {
                        setImage(R.mipmap.icon_item_remove)
                        setWidth(width)
                        setHeight(height)
                        setBackgroundColorResource(R.color.pink)
                    }
                    addSubItem.apply {
                        setImage(R.mipmap.icon_item_addsub)
                        setWidth(width)
                        setHeight(height)
                        setBackgroundColorResource(R.color.orange)
                    }
                    finishItem.apply {
                        setImage(R.mipmap.icon_item_finish)
                        setWidth(width)
                        setHeight(height)
                        setBackgroundColorResource(R.color.green)
                    }
                    startItem.apply {
                        setImage(R.mipmap.home_start_w)
                        setWidth(width)
                        setHeight(height)
                        setBackgroundColorResource(R.color.green)

                    }
                    leftMenu?.addMenuItem(startItem)
                    if (layoutId == R.layout.item_task) {
                        rightMenu?.addMenuItem(finishItem)
                        rightMenu?.addMenuItem(addSubItem)
                        rightMenu?.addMenuItem(removeItem)
                    }
                }


            }

            setOnItemMenuClickListener { menuBridge, adapterPosition ->
                menuBridge.closeMenu()
                val direction = menuBridge.direction
                // 菜单在Item中的Position：
                val menuPosition = menuBridge.position
            }


            treeRecycleAdapter = TreeRecyclerAdapter(TreeRecyclerType.SHOW_EXPAND)
            treeRecycleAdapter?.setOnItemClickListener { viewHolder, position ->
                val item = treeRecycleAdapter?.getData(position)
                item?.onClick(viewHolder)
            }
            adapter = treeRecycleAdapter
        }

        bottomView.apply {
            setBottomViewListener(object : BottomView.BottomViewListener {
                override fun action(actionType: BottomView.ActionType) {
                    Logger.e("BottomView actionType is $actionType")
                    when (actionType) {
                        BottomView.ActionType.ACTION_CLICK_DONE -> {

                        }
                        BottomView.ActionType.ACTION_CLICK_STATISTICS -> {

                        }
                        BottomView.ActionType.ACTION_CLICK_SETTING -> {

                        }
                        BottomView.ActionType.ACTION_CLICK_RANKING -> {

                        }
                        BottomView.ActionType.ACTION_CLICK_COMPLETE -> {

                        }
                        BottomView.ActionType.ACTION_CLICK_CLOSE_INPUT -> {

                        }
                        BottomView.ActionType.ACTION_CLICK_CLOCK -> {
                            tomatoClockView?.startTomatoClock(TomatoClockView.JUST_TOMATO_TIME)

                        }
                        BottomView.ActionType.ACTION_CLICK_CALENDAR -> {

                        }
                    }
                }
            })

        }

    }

    override fun initData() {
        super.initData()
        getCateListData()
        getTaskData()
    }

    override fun onDestroy() {
        super.onDestroy()
        tomatoClockView?.releaseTimeCounter()
    }

    private fun getCateListData() {
        Logger.e("getCateListData")
        val colorList = arrayOf("#f95653", "#f77360", "#f49256", "#f9b53a")
        for (i in 0..3) {
            val cate = Cate()
            cate.apply {
                if (i == 1) {
                    title =
                        "titletitletititletitletitlet $i"
                } else {
                    title = "title$i"
                }

                colorString = colorList[i]
            }
            cateList.add(cate)
        }
        cateList.add(Cate().apply { isCreateItem = true })
        homeCateAdapter?.notifyDataSetChanged()
    }

    private fun getTaskData() {
        taskGroupList.clear()
        for (index in 1..3) {
            val taskGroup = ViewModel.TaskGroupItem()
            taskGroup.apply {
                itemName = when (index) {
                    1 -> "今日"
                    2 -> "待办"
                    else -> "已完成"
                }

                val potatoItemList = arrayListOf<ViewModel.TaskGroupItem.PotatoItem>()
                for (ind in 1..6) {
                    val potatoItem = ViewModel.TaskGroupItem.PotatoItem()
                    val potato = Potato()
                    potato.apply {
                        title = if (ind == 1) {
                            "potatoName potatoName potatoName potatoName potatoName potatoName$ind"
                        } else {
                            "potatoName$ind"
                        }
                    }

                    val subPotatoList =
                        arrayListOf<ViewModel.TaskGroupItem.PotatoItem.SubPotatoItem>()
                    for (index1 in 1..3) {
                        val subPotatoItem = ViewModel.TaskGroupItem.PotatoItem.SubPotatoItem()
                        subPotatoItem.apply {
                            this.subPotato = PotatoSub().apply { title = "potatoSubName$index1" }
                        }
                    }

                    potatoItem.apply {
                        this.potato = potato
                        this.subPotatos = subPotatoList
                    }

                    potatoItemList.add(potatoItem)
                }
                potatos = potatoItemList
            }

            taskGroupList.add(taskGroup)
        }

        val items = ItemHelperFactory.createItems(taskGroupList)
        Logger.e("items is " + items.toString())
        for (i in items.indices) {
            val treeItem = items[i] as TreeItemGroup<*>
            treeItem.isExpand = false
        }
        //添加到adapter
        treeRecycleAdapter?.itemManager?.replaceAllItem(items)
    }

    private fun showOrDismissDrawer(isShow: Boolean = false) {
        if (isShow) {
            measureDrawerLayout.openDrawer(Gravity.RIGHT)
        } else {
            if (measureDrawerLayout.isDrawerOpen(Gravity.RIGHT)) {
                measureDrawerLayout.closeDrawer(Gravity.RIGHT)
            }
        }

    }

}